package com.example.cloud.service.basic.config.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cloud.dao.basic.config.SmsTemplateRepository;
import com.example.cloud.model.config.SmsTemplate;
import com.example.cloud.model.system.User;
import com.example.cloud.service.basic.config.SmsTemplateService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by wangtao on 2018/6/12.
 */
@Service
public class SmsTemplateServiceImpl implements SmsTemplateService {

    private static final Logger logger = Logger.getLogger(SmsTemplateServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private SmsTemplateRepository smsTemplateRepository;

    @Override
    public SmsTemplate findOne(Long id) {
        return smsTemplateRepository.findOne(id);
    }

    @Override
    public List<SmsTemplate> findAll() {
        return smsTemplateRepository.findByAccountIdAndDeleteFlag(RequestUtil.getLoginUser().getAccountId(), 0);
    }

    @Override
    public void doSave(SmsTemplate record) {
        if(record.getId() == null){
            User user = RequestUtil.getLoginUser();
            record.setAccountId(user.getAccountId());
            if(StringUtils.isNotBlank(record.getAnalysisContent())){
                JSONArray ja = new JSONArray();
                JSONArray jsonArray = JSON.parseArray(record.getAnalysisContent());
                for (Object o : jsonArray) {
                    JSONObject j = (JSONObject)o;
                    JSONObject json = new JSONObject();
                    json.put(j.getString("key"), j.getString("value"));
                    ja.add(json);
                }
                record.setAnalysisContent(JSON.toJSONString(ja));
            }
        }
        BusinessUtil.appendRecord(record);
        smsTemplateRepository.save(record);
    }

    @Override
    public void doDelete(List<Long> ids) {
        smsTemplateRepository.deleteByIdIn(ids);
    }
}
